//
//  TFChatTableViewController.swift
//  TalkfunSDKDemo
//
//  Created by 莫瑞权 on 2022/4/26.
//  Copyright © 2022 Talkfun. All rights reserved.
//

import UIKit

class TFChatTableViewController: UITableViewController,TFChatCellDelegate,TFVoteCellDelegate {
    

    //滚动到回复的cell
    @objc public var replyrow:NSInteger = 0
    @objc public let nodataView = UIView()
    @objc public let dataSource = NSMutableArray()
    @objc public weak var delegate : TFChatTableViewControllerDelegate?
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        self.tableView.separatorStyle = .none
        
        self.tableView.register(TFVoteCell.self, forCellReuseIdentifier: "TFVoteCell")
        self.tableView.register(TFMemberCell.self, forCellReuseIdentifier: "TFMemberCell")
        self.tableView.register(TFDisableChatCell.self, forCellReuseIdentifier: "TFDisableChatCell")
        self.tableView.register(TFQuestionCell.self, forCellReuseIdentifier: "TFQuestionCell")
        self.tableView.register(TFChatCell.self, forCellReuseIdentifier: "TFChatCell")
    }

    // MARK: - Table view data source


    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return self.dataSource.count
    }
    func recalculateCellHeight()

    {
        self.tableView.reloadData()
        
        self.scorellToreplyCell()
        
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }
    @objc public func scorellToreplyCell()
     {
         if self.dataSource.count>0 {
             let indexpath = NSIndexPath.init(row: self.dataSource.count - 1, section: 0)
             self.tableView.scrollToRow(at: indexpath as IndexPath, at: .bottom, animated: true)
         }
         
         
     }
    /**更新聊天信息*/
    @objc public func update_Chat(model:TF_LivingChatData)
    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }
    //删除聊天数据
    @objc func ChatDel(uuid:String)
    {
        let copyArray = NSMutableArray.init(array: self.dataSource)
        for i in 0..<copyArray.count {
            let obj = self.dataSource[i] as! NSObject
            if (obj is TF_LivingChatData) {
                let data = obj as! TF_LivingChatData
                
                if (data.uuid == uuid) {
                   
                        self.dataSource.remove(data)

                        break;
                    }
                
            }
        }
       
        self.tableView.reloadData()
      
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }

    /**更新通知信息*/
    @objc public func updata_Notice(model:TFBroadcast)
    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }

    /**更新禁言信息*/
    @objc public func update_disabelChat(model:TFDisableChatModel)

    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }

    /**更新投票信息*/
    @objc public func update_Vote(model:TFVoteData)
    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }

    /**更新抽奖*/
    @objc public func update_Lottery(model:TFLotteryStop)

    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }

    /**回复提问*/
    @objc public func pePly_Question(model:TFQuestionData)
    {
        let copyArray = NSMutableArray.init(array: self.dataSource)
        
        var answer:Bool = false
        for i in 0..<copyArray.count {

            let obj = copyArray[i] as! NSObject
            if (obj is TFQuestionData) {
                let data = obj as! TFQuestionData
                //本地自己的提问中是否查询到
                 if (data.qid == model.qid) {
                     answer = true
                     self.dataSource.replaceObject(at: i, with: model)
                     //[self.dataSource replaceObjectAtIndex:i withObject:model];
                     if (model.isMe) {
                         self.replyrow = i;
                       
                     }
                    break;
                }
            }

        }
        
        //新增新的
        if (answer==false) {
            self.dataSource.add(model)
    
        }
        self.tableView.reloadData()
      
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }


    /**接收提问*/
    @objc public func update_Question(model:TFQuestionData)
    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }
    /**删除提问*/
    @objc public func remove_Question(model:TFQuestionData)

    {
        let copyArray = NSMutableArray.init(array: self.dataSource)
        for i in 0..<copyArray.count {
            let obj = self.dataSource[i] as! NSObject
            if (obj is TFQuestionData) {
                let data = obj as! TFQuestionData
                if (data.qid == model.qid) {
                    if (model.deleteQuestionID.count > 0) {
                        
                        for i in 0..<data.answer.count {
                            let answer = data.answer[i] as! TFQuestionAnswer

                            if (answer.qid == model.deleteQuestionID) {

                                data.answer.remove(answer)
                                break;
                            }
                        }
                    } else {
                        self.dataSource.remove(data)

                        break;
                    }
                }
            }
        }
       
        self.tableView.reloadData()
      
        if (self.dataSource.count > 0) {
            self.nodataView.isHidden = true
        } else {
            self.nodataView.isHidden = false
        }
    }



    /**其他用户进入直播间*/
    @objc public func update_Join(model:TFMember)
    {
        self.dataSource.add(model)
        self.recalculateCellHeight()
    }


    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let obj = self.dataSource[indexPath.row] as! NSObject
        if (obj is TFBroadcast ) { //通知
            
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFVoteCell") as! TFVoteCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = false
            cell.tf_width = self.view.frame.size.width
            cell.backgroundColor = UIColor.clear
            
            let model = self.dataSource[indexPath.row] as! TFBroadcast
            cell.model = model
            cell.delegate = nil
            return cell
        } else if (obj is TFVoteData) {  //投票
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFVoteCell") as! TFVoteCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = false
            cell.tf_width = self.view.frame.size.width
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .default;
            let model = self.dataSource[indexPath.row] as! TFVoteData
            cell.votemodel = model;
            cell.delegate = self;
            return cell;
        } else if (obj is TFLotteryStop) { // 抽奖
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFVoteCell") as! TFVoteCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = false
            cell.tf_width = self.view.frame.size.width
            cell.backgroundColor = UIColor.clear
            cell.selectionStyle = .none
            let model = self.dataSource[indexPath.row] as! TFLotteryStop
            cell.LotteryStopmodel = model;
            cell.delegate = nil;
            return cell;
        }
        else if (obj is TFDisableChatModel) { //禁言
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFDisableChatCell") as! TFDisableChatCell
            cell.selectionStyle = .none
            cell.isOrientationLandscape = false
            cell.backgroundColor = UIColor.clear
            let model = self.dataSource[indexPath.row] as! TFDisableChatModel
            cell.model = model;
            return cell;
        } else if (obj is TFQuestionData ) { // 提问
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFQuestionCell") as! TFQuestionCell
     
            cell.selectionStyle = .none
            cell.cellwidth = self.view.frame.size.width;
            cell.isOrientationLandscape = false
            cell.isQuestion = false
            cell.isChatArea = false
            cell.backgroundColor = UIColor.clear

            let model = self.dataSource[indexPath.row] as! TFQuestionData
        
            cell.model = model;
            return cell;
        } else if (obj is TFMember) {
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFMemberCell") as! TFMemberCell
            cell.selectionStyle = .none
            cell.backgroundColor = UIColor.clear
            cell.cellwidth = self.view.frame.size.width;
            cell.isOrientationLandscape = false
            let model = self.dataSource[indexPath.row] as! TFMember
            cell.model = model;
            return cell;
            
        } else {  //聊天
            let cell = tableView.dequeueReusableCell(withIdentifier:"TFChatCell") as! TFChatCell
            
            cell.selectionStyle = .none
            cell.cellwidth =  self.view.frame.size.width
            cell.backgroundColor = UIColor.clear

            cell.isOrientationLandscape = false
            
            let model = self.dataSource[indexPath.row] as! TF_LivingChatData
               
            cell.model = model;

            cell.delegate = self;
            return cell;
        }
        

  
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let obj = self.dataSource[indexPath.row] as! NSObject
        
         if (obj is TFVoteData) { //投票
             let model = self.dataSource[indexPath.row] as! TFVoteData
             
             self.clickVote(model)

           
        }
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let result = self.dataSource[indexPath.row] as! NSObject
        let height = TFHorizontalChatView.getHeight(result: result,width: self.tableView.frame.width,interval:8,imageWidth:96)
        return height;

    }
    
   
    func urlClick(url: NSString) {
        
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFHorizontalChatViewDelegate.HorChat_clickToUrl(_:))))!{
           
            self.delegate?.HorChat_clickToUrl(url)
        }
       
    }
    
    func clickVote(_ model: TFVoteData) {
        
        if self.delegate != nil && (self.delegate?.responds(to: #selector(TFHorizontalChatViewDelegate.HorChat_clickToUrl(_:))))!{
           
            self.delegate?.HorVote_clickToDetail(model)
        }
    }
    
    @objc public func createUI()
     {

         self.nodataView.frame = self.view.bounds
         self.view.addSubview(self.nodataView)
         
         let noImg = UIImageView()
         noImg.frame = CGRect(x: (self.nodataView.frame.size.width-200)/2.0, y: 60, width: 200, height: 150)
         noImg.image = UIImage.init(named: "HTLive.bundle/Default page_ask")
         self.nodataView.addSubview(noImg)
         
         let noLabel = UILabel()
         noLabel.text = "暂无聊天"
         noLabel.font = UIFont.PingFang(size: 16)
         noLabel.textColor = UIColor(red: 20/255.0, green: 23/255.0, blue: 26/255.0, alpha: 1)
         noLabel.textAlignment = .center
         noLabel.frame = CGRect(x: 0, y: 176, width: self.nodataView.frame.size.width, height: 22)
         self.nodataView.addSubview(noLabel)
         
     }
}
@objc protocol TFChatTableViewControllerDelegate : NSObjectProtocol {
    // 点击超链接
    func HorChat_clickToUrl(_ url :NSString)
    //投票结果
    func HorVote_clickToDetail(_ model :TFVoteData)

}
